<?php
/**
 * Jishupu-Laravel-Vue-Admin
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Controllers;

use App\Filters\InfoCategoryFilter;
use App\Http\Requests\InfoCategoryRequest;
use App\Http\Resources\InfoCategoryCollection;
use App\Http\Resources\InfoCategoryResource;
use App\Models\Info;
use App\Models\InfoCategory;
use App\Services\AttachmentService;
use App\Services\InfoCategoryService;
use App\Services\TreeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 信息栏目分类模块
 * Class InfoCategoryController
 * @package App\Http\Controllers
 */
class InfoCategoryController extends Controller
{

    /**
     * 列表
     * @param InfoCategoryFilter $filter
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(InfoCategoryFilter $filter)
    {
        $filter = InfoCategory::filter($filter)->get();
        $collection = InfoCategoryCollection::make($filter)->toArray(null);
        $items = TreeService::make($collection['items']);
        return $this->success('', ['items' => $items, 'total' => count($collection['items'])]);
    }

    /**
     * 添加
     * @param InfoCategoryRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(InfoCategoryRequest $request)
    {
        $data = $request->validate('store');
        $info_category = new InfoCategory($data);
        if (!$info_category->save()) return $this->errorStored();
        // 绑定附件
        AttachmentService::bind($info_category, 'cover_image', $info_category->cover_image);
        return $this->successStored();
    }

    /**
     * 查看
     * @param InfoCategory $info_category
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(InfoCategory $info_category)
    {
        $infoCategory = InfoCategoryResource::make($info_category)->except(['created_at', 'updated_at', 'sort', 'info_model'])->toArray(null);
        return $this->success('', $infoCategory);
    }

    /**
     * 更新
     * @param InfoCategoryRequest $request
     * @param InfoCategory $info_category
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(InfoCategoryRequest $request, InfoCategory $info_category)
    {
        $data = $request->validate('update');
        if (!$info_category->update($data)) return $this->errorUpdated();
        // 绑定附件
        AttachmentService::bind($info_category, 'cover_image', $info_category->cover_image);
        return $this->successUpdated();
    }

    /**
     * 删除
     * @param InfoCategory $info_category
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(InfoCategory $info_category)
    {
        DB::beginTransaction();
        try {
            $subCategory = InfoCategory::where('parent_id', $info_category->id)->first();
            // 存在下级则禁止删除
            if ($subCategory) {
                return $this->error(__('infoCategory.prohibit_delete_with_subs'));
            }
            // 栏目下存在数据禁止删除
            if ($info_category->type == 2) {
                $info = Info::where('info_category_id', $info_category->id)->first();
                if ($info) {
                    return $this->error(__('infoCategory.prohibit_delete_with_data'));
                }
            }
            $info_category->delete();
            DB::commit();
            return $this->successDestoryed();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->exception($e->getMessage())->errorDestoryed();
        }
    }

    /**
     * 更新状态
     * @param InfoCategoryRequest $request
     * @param InfoCategory $info_category
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateStatus(InfoCategoryRequest $request, InfoCategory $info_category)
    {
        $data = $request->validate('updateStatus');
        if (!$info_category->update($data)) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 更新排序
     * @param InfoCategoryRequest $request
     * @param InfoCategory $info_category
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateSort(InfoCategoryRequest $request, InfoCategory $info_category)
    {
        $data = $request->validate('updateSort');
        if (!$info_category->batchUpdate($data['sort'])) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 上一级选择栏目树配置
     * @param $id // 当前栏目id
     * @return \Illuminate\Http\JsonResponse
     */
    public function parentTreeConfig($id)
    {
        return $this->success('', InfoCategoryService::getParentTree($id));
    }

    /**
     * 获取导航模块、角色模块所需栏目树数据
     * @param $id // 当前栏目id
     * @return \Illuminate\Http\JsonResponse
     */
    public function categoryTreeConfig($id)
    {
        return $this->success('', InfoCategoryService::getParentTree($id, false));
    }
}
